package simco.framework.gui.utils;

import java.io.IOException;

import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;

/**
 * Trida slouzici jako utilitka pro logovani. Umoznuje ziskat
 * preddefinovany logger pro logovani udalosti v aplikaci.
 * 
 * @author Matej Prokop, mythge@students.zcu.cz
 *
 */
public class LoggingUtil 
{
	/**
	 * Udrzuje preddefinovane jmeno loggera
	 */
	private static final String LOGGER_NAME = "simco.framework.gui";
	
	private final static String PATTERN = "%n" +  
	    "Event time and date: %d{ISO8601} %n" +
	    "Milliseconds since program start: %r %n" +
	    "Location of log event: %l %n" +
	    "Message: %m %n"; 
	
	/**
	 * Preddefinovane jmeno souboru, do ktereho budou ukladany 
	 * logovane zaznamy
	 */
	public static final String GUI_LOGGIN_FILE_NAME = "simcoGui.log";
	
	/**
	 * Reference na preddefinovany logger
	 */
	private static Logger logger = null;
	
	/**
	 * Reference na chybu vzniklou pri inicializaci preddefinovaneho
	 * loggeera.
	 */
	private static IOException initError = null;
	
	/**
	 * Vrati referenci na preddefinovaneho loggera.
	 * 
	 * @return preddefinovany logger
	 */
	public static Logger getGuiLogger()
	{
		ensureInicialization(Configuration.getApplicationPath() +
				GUI_LOGGIN_FILE_NAME);
		return logger;
	}
	
	/**
	 * Testuje jestli byl preddefinovany logger inicializovany,
	 * pokud ne provede inicializaci.
	 * 
	 * @param guiLoggingFile jmono souboru do, ktereho budou zapisovany
	 * zaznamy loggerem
	 */
	private synchronized static void ensureInicialization(String guiLoggingFile)
	{
		if(logger == null)
		{			
			logger = Logger.getLogger(LOGGER_NAME);
			logger.setLevel(Level.INFO);
					
			FileAppender appender;
			try 
			{
				appender = new FileAppender(new PatternLayout(PATTERN), guiLoggingFile);
				appender.activateOptions();
				logger.addAppender(appender);
			} 
			catch (IOException e) 
			{
				initError = e;
			}
		}
	}

	/**
	 * Vraci chybu pri inicializaci loggera. 
	 * 
	 * @return reference na vyjimku, ktera byla vyhozena pri inicializaci loggera,
	 * pokud k vyjimce nedoslo vraci null
	 */
	public static IOException getInitError() 
	{
		return initError;
	}
	
	
}
